﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Com.Toook.Common;
using System.Data.OleDb;

public partial class nst_article_ArticleEdit : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            InitDropDownListType();
            InitData();
        }
    }
    protected void ButtonEdit_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        bool isUpdateOneTable = btn.ID == "ButtonEditOneTable";

        LabelMsg.Text = "";
        if (!Page.IsValid)
        {
            LabelMsg.Text = "输入内容不合法";
            return;
        }

        OleDbConnection con = AccessHelper.GetConnection();
        OleDbCommand cmd = new OleDbCommand();
        cmd.Connection = con;
        string sql;
        if (ddlPage.SelectedValue == "1")//修改 PublishArticle
        {
            if (isUpdateOneTable)//在第一页点击只修改内容、评分（PublishArticle）
            {
                sql = "update PublishArticle set content=@content, score=@score " +
                    " where typePageId=@typePageId ";
                cmd.Parameters.Add("@content", OleDbType.LongVarWChar).Value = txtContent.Text;
                cmd.Parameters.Add("@score", OleDbType.Integer).Value = ddlScore.SelectedValue;
                cmd.Parameters.Add("@typePageId", OleDbType.Integer).Value = lblTypePageId.Text;

            }
            else//在第一页点击修改标题、作者、来源
            {
                sql = "update PublishArticle set title=@title, author=@author, sourceSite=@sourceSite " +
                     " where typePageId=@typePageId ";
                    
                cmd.Parameters.Add("@title", OleDbType.VarWChar, 30).Value = txtTitle.Text;        
                cmd.Parameters.Add("@author", OleDbType.VarWChar, 50).Value = txtAuthor.Text;
                cmd.Parameters.Add("@sourceSite", OleDbType.VarWChar, 50).Value = txtSourceSite.Text;
                cmd.Parameters.Add("@typePageId", OleDbType.Integer).Value = lblTypePageId.Text;
            }
        }
        else//在后面页修改 PublishArticleMorePage content
        {
            sql = "update PublishArticleMorePage set content=@content " +
                " where typePageId=@typePageId and pageNum=@pageNum ";
            cmd.Parameters.Add("@content", OleDbType.LongVarWChar).Value = txtContent.Text;            
            cmd.Parameters.Add("@typePageId", OleDbType.Integer).Value = lblTypePageId.Text;
            cmd.Parameters.Add("@pageNum", OleDbType.Integer).Value = ddlPage.SelectedValue;
        }          
        
        try
        {
            con.Open();
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
            if (!isUpdateOneTable)//更新两个表的标题、作者、来源等，想要更新PublishArticleMorePage
            {
                cmd.CommandText = "update PublishArticleMorePage set title=@title, author=@author, sourceSite=@sourceSite " +
                    " where typePageId=@typePageId";
                cmd.ExecuteNonQuery();
            }
            
            LabelMsg.Text = "修改成功：" + txtTitle.Text;            
        }
        catch (Exception ex)
        {
            LabelMsg.Text = "修改失败" + ex.Message;
            LogHelper.Log.Error("修改article失败。typePageId=" + lblTypePageId.Text, ex);
        }
        finally
        {
            con.Close();
        }
    }
    protected void ButtonDeleteMorePage_Click(object sender, EventArgs e)
    {
        string sql = "delete from PublishArticleMorePage where typePageId=@typePageId";
        OleDbConnection con = AccessHelper.GetConnection();
        OleDbCommand cmd = new OleDbCommand(sql, con);        
        cmd.Parameters.Add("@typePageId", OleDbType.Integer).Value = lblTypePageId.Text;

        try
        {
            con.Open();
            cmd.ExecuteNonQuery();

            cmd.CommandText = "update PublishArticle set totalPage=1 where typePageId=@typePageId";
            cmd.ExecuteNonQuery();
            LabelMsg.Text = "删除其他页成功。";
            ddlPage.Items.Clear();
            ddlPage.Items.Add("1");
        }
        catch (Exception ex)
        {
            LabelMsg.Text = "删除失败" + ex.Message;
            LogHelper.Log.Error("删除PublishArticleMorePage失败。typePageId=" + lblTypePageId.Text, ex);
        }
        finally
        {
            con.Close();
        }
    }
    private void InitDropDownListType()
    {
        DataRow[] rows = PageData.SelectParamRows("parentId=60");
        foreach (DataRow row in rows)
        {
            ddlType.Items.Add(new ListItem(row["typeName"].ToString(), row["typeId"].ToString()));
        }
    }
    /// <summary>
    /// 获取文章数据，填充文本框、下拉列表等
    /// </summary>
    private void InitData()
    {
        string typePageId = Request["id"];
        int id = 0;
        if (string.IsNullOrEmpty(typePageId) || !int.TryParse(typePageId, out id))
        {
            return;
        }
        LabelMsg.Text = "";
        lblTypePageId.Text = typePageId;
        string type = typePageId.Substring(0, 2);        
        ParamHelper.SetDropDownListSelectedIndex(ddlType, type);

        string sql;
        string currentPage = ddlPage.SelectedValue;
        if (currentPage == "1")//第一页在PublishArticle表
        {
            sql = "select title, typePageId, author, sourceSite, totalPage, content, score from PublishArticle where typePageId=" + typePageId;
        }
        else//后面的页在PublishArticleMorePage表
        {
            sql = "select title, typePageId, author, sourceSite, totalPage, content from PublishArticleMorePage where typePageId=" + typePageId + " and pageNum=" + currentPage;
        }
        OleDbConnection con = AccessHelper.GetConnection();
        OleDbCommand cmd = new OleDbCommand(sql, con);
        OleDbDataReader reader = null;
        int totalPage = 1;
        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                txtAuthor.Text = reader["author"].ToString();
                txtContent.Text = reader["content"].ToString();
                txtSourceSite.Text = reader["sourceSite"].ToString();
                txtTitle.Text = reader["title"].ToString();
                int.TryParse(reader["totalPage"].ToString(), out totalPage);
                if (totalPage > 1)
                {
                    ddlPage.Items.Clear();
                    for (int i = 1; i <= totalPage; i++)
                    {
                        ddlPage.Items.Add(i.ToString());
                    }
                    ParamHelper.SetDropDownListSelectedIndex(ddlPage, currentPage);
                }

                if (currentPage == "1")
                {
                    ParamHelper.SetDropDownListSelectedIndex(ddlScore, reader["score"].ToString());
                }

                SetEnable(currentPage == "1");
            }
            else
            {
                LabelMsg.Text = "没有读取到数据";
            }           
        }
        catch (Exception ex)
        {
            LabelMsg.Text = "读取到数据出错";
            LogHelper.Log.Error("编辑文章时查询数据出错", ex);
        }
        finally
        {
            AccessHelper.CloseDbResource(con, reader);
        }
    }
    /// <summary>
    /// 如果是第一页，标题、来源、作者可以编辑、其他页不能编辑
    /// </summary>
    /// <param name="isFirstPage"></param>
    private void SetEnable(bool isFirstPage)
    {
        if (isFirstPage)
        {
            txtAuthor.Enabled = true;
            txtSourceSite.Enabled = true;
            txtTitle.Enabled = true;
            ButtonEditTwoTable.Enabled = true;
        }
        else
        {
            txtAuthor.Enabled = false;
            txtSourceSite.Enabled = false;
            txtTitle.Enabled = false;
            ButtonEditTwoTable.Enabled = false;
        }
    }
    protected void ddlPage_SelectedIndexChanged(object sender, EventArgs e)
    {
        InitData();
    }

    
}
